﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace StockAnalyst2.AttachedProperties
{
	internal class AllowTargetUpdatedNotification
	{
		public static bool GetAllowTargetUpdated(DependencyObject obj)
		{
			return (bool)obj.GetValue(AllowTargetUpdatedProperty);
		}

		public static void SetAllowTargetUpdated(DependencyObject obj, bool value)
		{
			obj.SetValue(AllowTargetUpdatedProperty, value);
		}

		// Using a DependencyProperty as the backing store for AllowTargetUpdated.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty AllowTargetUpdatedProperty = DependencyProperty.RegisterAttached("AllowTargetUpdated", typeof(bool), typeof(AllowTargetUpdatedNotification), new UIPropertyMetadata(false, OnAllowTargetUpdatedPropertyChanged));

		private static void OnAllowTargetUpdatedPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
		{
			FrameworkElement frameworkElement = obj as FrameworkElement;

			if (frameworkElement != null)
			{
				BindingExpression bindingExpression = frameworkElement.GetBindingExpression(TextBlock.TextProperty);
				if (bindingExpression != null)
				{
					Binding binding = bindingExpression.ParentBinding;
					Binding newBinding = new Binding(binding.Path.Path);
					newBinding.NotifyOnTargetUpdated = (bool)e.NewValue;
					newBinding.TargetNullValue = binding.TargetNullValue;
					newBinding.StringFormat = binding.StringFormat;
					
					BindingOperations.ClearBinding(frameworkElement, TextBox.TextProperty);
					frameworkElement.SetBinding(TextBlock.TextProperty, newBinding);
				}
			}
		}
	}
}
